class CanvasBoard {
	constructor(canvasElement, imageSrc, onImageLoad) {
		this.canvas = canvasElement;
		this.ctx = this.canvas.getContext('2d');
		this.imageSrc = imageSrc;
		this.onImageLoad = onImageLoad || (() => { }); // 初始化回调函数，默认为空函数
		this.textInput = null; // 新增文本框
		this.isTextMode = false; // 新增文本模式标志
		this.init();
	}

	init() {
		this.isDrawing = false;
		this.currentTool = 'pencil';
		this.color = '#000000';
		this.lineWidth = 4;
		this.history = [];
		this.currentHistoryIndex = -1;
		this.textPosition = { x: 0, y: 0 }; // 新增文本位置

		this.loadImage();
		this.setupEventListeners();
	}

	loadImage() {
		this.image = new Image();
		this.image.crossOrigin = "Anonymous";
		this.image.src = this.imageSrc;
		this.image.onload = () => {
			this.canvas.width = this.canvas.parentNode.clientWidth; //this.image.width;
			this.canvas.height = this.canvas.parentNode.clientHeight; //this.image.height;
			this.image.style = "object-fit: contain;";
			this.redraw();
			this.onImageLoad(); // 图片加载完成后调用回调
		};
		this.image.onerror = () => {
			this.onImageLoad(); // 图片加载完成后调用回调
		};
	}

	redraw() {
		this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

		// 确保图片已加载
		if (this.image && this.image.complete && this.image.naturalWidth !== 0) {
			// 保持比例，居中显示
			const scale = Math.min(
				this.canvas.width / this.image.width,
				this.canvas.height / this.image.height
			);
			const width = this.image.width * scale;
			const height = this.image.height * scale;
			const x = (this.canvas.width - width) / 2;
			const y = (this.canvas.height - height) / 2;
			this.ctx.drawImage(this.image, x, y, width, height);
			// 直接拉伸图片填充整个canvas
			// this.ctx.drawImage(this.image, 0, 0, this.canvas.width, this.canvas.height);
		}
		if (this.currentHistoryIndex >= 0) {
			const img = new Image();
			img.src = this.history[this.currentHistoryIndex];
			img.onload = () => this.ctx.drawImage(img, 0, 0);
		}
	}

	setupEventListeners() {
		this.canvas.addEventListener('mousedown', (e) => this.startDrawing(e));
		this.canvas.addEventListener('mousemove', (e) => this.draw(e));
		this.canvas.addEventListener('mouseup', () => this.stopDrawing());
		this.canvas.addEventListener('mouseleave', () => this.stopDrawing());

		// 新增文本框事件监听
		this.canvas.addEventListener('click', (e) => {
			if (this.isTextMode) {
				this.showTextInput(e);
				this.isTextMode = false; // 关闭文本模式
			}
		});
	}

	startDrawing(e) {
		this.isDrawing = true;
		this.startX = e.offsetX;
		this.startY = e.offsetY;
		this.ctx.beginPath();
		this.ctx.moveTo(this.startX, this.startY);
	}

	draw(e) {
		if (!this.isDrawing) return;

		const x = e.offsetX;
		const y = e.offsetY;

		this.ctx.strokeStyle = this.color;
		this.ctx.lineWidth = this.lineWidth;
		this.ctx.lineCap = 'round';

		switch (this.currentTool) {
			case 'pencil':
				this.ctx.lineTo(x, y);
				this.ctx.stroke();
				break;
			case 'arrow':
				// 使用临时canvas绘制预览
				const tempCanvasArrow = document.createElement('canvas');
				tempCanvasArrow.width = this.canvas.width;
				tempCanvasArrow.height = this.canvas.height;
				const tempArrowCtx = tempCanvasArrow.getContext('2d');

				// 设置临时canvas的样式
				tempArrowCtx.lineWidth = this.lineWidth;
				tempArrowCtx.strokeStyle = this.color;
				tempArrowCtx.lineCap = 'round';

				// 绘制背景和历史记录
				if (this.image && this.image.complete && this.image.naturalWidth !== 0) {
					const scale = Math.min(
						this.canvas.width / this.image.width,
						this.canvas.height / this.image.height
					);
					const width = this.image.width * scale;
					const height = this.image.height * scale;
					const xPos = (this.canvas.width - width) / 2;
					const yPos = (this.canvas.height - height) / 2;
					tempArrowCtx.drawImage(this.image, xPos, yPos, width, height);
				}
				if (this.currentHistoryIndex >= 0) {
					const img = new Image();
					img.src = this.history[this.currentHistoryIndex];
					img.onload = () => {
						tempArrowCtx.drawImage(img, 0, 0);

						// 绘制箭头
						this.drawArrow(tempArrowCtx, this.startX, this.startY, x, y);

						// 将预览绘制到主canvas
						this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
						this.ctx.drawImage(tempCanvasArrow, 0, 0);
					};
				} else {
					// 绘制箭头
					this.drawArrow(tempArrowCtx, this.startX, this.startY, x, y);

					// 将预览绘制到主canvas
					this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
					this.ctx.drawImage(tempCanvasArrow, 0, 0);
				}
				break;
			case 'rectangle':
				// 使用临时canvas绘制预览
				const tempCanvas = document.createElement('canvas');
				tempCanvas.width = this.canvas.width;
				tempCanvas.height = this.canvas.height;
				const tempCtx = tempCanvas.getContext('2d');

				// 设置临时canvas的线宽
				tempCtx.lineWidth = this.lineWidth;
				tempCtx.strokeStyle = this.color;
				tempCtx.lineCap = 'round';

				// 绘制背景和历史记录
				if (this.image && this.image.complete && this.image.naturalWidth !== 0) {
					const scale = Math.min(
						this.canvas.width / this.image.width,
						this.canvas.height / this.image.height
					);
					const width = this.image.width * scale;
					const height = this.image.height * scale;
					const xPos = (this.canvas.width - width) / 2;
					const yPos = (this.canvas.height - height) / 2;
					tempCtx.drawImage(this.image, xPos, yPos, width, height);
				}
				if (this.currentHistoryIndex >= 0) {
					const img = new Image();
					img.src = this.history[this.currentHistoryIndex];
					img.onload = () => {
						tempCtx.drawImage(img, 0, 0);
						// 绘制当前矩形
						tempCtx.strokeRect(this.startX, this.startY, x - this.startX, y - this.startY);
						// 将预览绘制到主canvas
						this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
						this.ctx.drawImage(tempCanvas, 0, 0);
					};
				} else {
					// 绘制当前矩形
					tempCtx.strokeRect(this.startX, this.startY, x - this.startX, y - this.startY);
					// 将预览绘制到主canvas
					this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
					this.ctx.drawImage(tempCanvas, 0, 0);
				}
				break;
			case 'circle':
				// 使用临时canvas绘制预览
				const tempCanvasCircle = document.createElement('canvas');
				tempCanvasCircle.width = this.canvas.width;
				tempCanvasCircle.height = this.canvas.height;
				const tempCircleCtx = tempCanvasCircle.getContext('2d');

				// 设置临时canvas的样式
				tempCircleCtx.lineWidth = this.lineWidth;
				tempCircleCtx.strokeStyle = this.color;
				tempCircleCtx.lineCap = 'round';

				// 绘制背景和历史记录
				if (this.image && this.image.complete && this.image.naturalWidth !== 0) {
					const scale = Math.min(
						this.canvas.width / this.image.width,
						this.canvas.height / this.image.height
					);
					const width = this.image.width * scale;
					const height = this.image.height * scale;
					const xPos = (this.canvas.width - width) / 2;
					const yPos = (this.canvas.height - height) / 2;
					tempCircleCtx.drawImage(this.image, xPos, yPos, width, height);
				}
				if (this.currentHistoryIndex >= 0) {
					const img = new Image();
					img.src = this.history[this.currentHistoryIndex];
					img.onload = () => {
						tempCircleCtx.drawImage(img, 0, 0);

						// 计算最大半径
						const dx = x - this.startX;
						const dy = y - this.startY;
						const maxRadiusX = Math.min(
							Math.abs(this.startX - 0),
							Math.abs(this.startX - this.canvas.width)
						);
						const maxRadiusY = Math.min(
							Math.abs(this.startY - 0),
							Math.abs(this.startY - this.canvas.height)
						);

						// 计算实际半径
						const radiusX = Math.min(Math.abs(dx), maxRadiusX);
						const radiusY = Math.min(Math.abs(dy), maxRadiusY);

						// 判断是否需要反转
						const flipX = dx < 0 ? -1 : 1;
						const flipY = dy < 0 ? -1 : 1;

						// 保存当前状态
						tempCircleCtx.save();

						// 变换坐标系
						tempCircleCtx.translate(this.startX, this.startY);
						tempCircleCtx.scale(flipX * (radiusX / radiusY), flipY);

						// 绘制椭圆
						tempCircleCtx.beginPath();
						tempCircleCtx.arc(0, 0, radiusY, 0, Math.PI * 2);
						tempCircleCtx.stroke();

						// 恢复状态
						tempCircleCtx.restore();

						// 将预览绘制到主canvas
						this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
						this.ctx.drawImage(tempCanvasCircle, 0, 0);
					};
				}
				break;
		}
	}

	// 新增方法：绘制箭头
	drawArrow(ctx, fromX, fromY, toX, toY) {
		const headLength = 15; // 箭头长度
		const angle = Math.atan2(toY - fromY, toX - fromX);

		// 绘制线条
		ctx.beginPath();
		ctx.moveTo(fromX, fromY);
		ctx.lineTo(toX, toY);
		ctx.stroke();

		// 绘制箭头
		ctx.beginPath();
		ctx.moveTo(toX, toY);
		ctx.lineTo(
			toX - headLength * Math.cos(angle - Math.PI / 6),
			toY - headLength * Math.sin(angle - Math.PI / 6)
		);
		ctx.moveTo(toX, toY);
		ctx.lineTo(
			toX - headLength * Math.cos(angle + Math.PI / 6),
			toY - headLength * Math.sin(angle + Math.PI / 6)
		);
		ctx.stroke();
	}

	// 新增方法：仅重绘背景图片
	redrawBackground() {
		if (this.image && this.image.complete && this.image.naturalWidth !== 0) {
			const scale = Math.min(
				this.canvas.width / this.image.width,
				this.canvas.height / this.image.height
			);
			const width = this.image.width * scale;
			const height = this.image.height * scale;
			const x = (this.canvas.width - width) / 2;
			const y = (this.canvas.height - height) / 2;
			this.ctx.drawImage(this.image, x, y, width, height);
		}
		if (this.currentHistoryIndex >= 0) {
			const img = new Image();
			img.src = this.history[this.currentHistoryIndex];
			img.onload = () => this.ctx.drawImage(img, 0, 0);
		}
	}

	stopDrawing() {
		if (this.isDrawing) {
			this.isDrawing = false;
			// 保存当前状态
			this.saveState();
			// 重绘以确保状态正确
			// this.redraw();
		}
	}

	saveState() {
		const dataUrl = this.canvas.toDataURL();
		this.history = this.history.slice(0, this.currentHistoryIndex + 1);
		this.history.push(dataUrl);
		this.currentHistoryIndex++;
	}

	setTool(tool) {
		this.currentTool = tool;
	}

	setColor(color) {
		this.color = color;
	}

	setLineWidth(width) {
		this.lineWidth = width;
	}

	undo() {
		if (this.currentHistoryIndex > 0) {
			this.currentHistoryIndex--;
			this.redraw();
		} else if (this.currentHistoryIndex === 0) {
			// 如果是最后一步，清空画布
			this.currentHistoryIndex = -1;
			this.redraw();
		}
	}

	redo() {
		if (this.currentHistoryIndex < this.history.length - 1) {
			this.currentHistoryIndex++;
			this.redraw();
		}
	}

	clear() {
		this.history = [];
		this.currentHistoryIndex = -1;
		this.redraw();
	}

	saveImage() {
		// 创建一个临时canvas
		const tempCanvas = document.createElement('canvas');
		tempCanvas.width = this.canvas.width;
		tempCanvas.height = this.canvas.height;
		const tempCtx = tempCanvas.getContext('2d');

		// 只绘制当前操作的内容
		if (this.currentHistoryIndex >= 0) {
			const img = new Image();
			img.src = this.history[this.currentHistoryIndex];
			img.onload = () => {
				tempCtx.drawImage(img, 0, 0);

				// 创建下载链接
				const link = document.createElement('a');
				link.download = 'annotated-image.png';
				link.href = tempCanvas.toDataURL();
				link.click();
			};
		} else {
			// 如果没有历史记录，保存空白图像
			const link = document.createElement('a');
			link.download = 'annotated-image.png';
			link.href = tempCanvas.toDataURL();
			link.click();
		}
	}

	// 新增方法：获取当前canvas的图像数据URL
	getImageDataURL(type = 'image/png', quality) {
		return this.canvas.toDataURL(type, quality);
	}

	// 新增方法：启用文本模式
	enableTextMode() {
		this.isTextMode = true;
	}
	// 修改showTextInput方法
	showTextInput(e) {
		// 移除旧的文本框
		if (this.textInput) {
			this.textInput.remove();
		}

		// 创建新的文本框
		this.textInput = document.createElement('input');
		this.textInput.type = 'text';
		this.textInput.style.position = 'absolute';
		this.textInput.style.left = `${e.clientX}px`;
		this.textInput.style.top = `${e.clientY}px`;
		this.textInput.style.border = '1px solid #000';
		this.textInput.style.padding = '5px';
		this.textInput.style.zIndex = '1000';

		// 保存点击位置
		this.textPosition = { x: e.offsetX, y: e.offsetY };

		// 添加回车确认事件
		this.textInput.addEventListener('keydown', (e) => {
			if (e.key === 'Enter') {
				this.addText(this.textInput.value, this.textPosition.x, this.textPosition.y);
				this.textInput.remove();
				this.textInput = null;
			}
		});

		// 添加失去焦点事件
		this.textInput.addEventListener('blur', () => {
			if (this.textInput) {
				this.addText(this.textInput.value, this.textPosition.x, this.textPosition.y);
				this.textInput.remove();
				this.textInput = null;
			}
		});

		document.body.appendChild(this.textInput);
		this.textInput.focus();
	}

	// 修改现有方法：添加文本
	addText(text, x, y) {
		this.ctx.font = '20px Arial';
		this.ctx.fillStyle = this.color;
		this.ctx.fillText(text, x, y);
		this.saveState();
	}
}

// 模块化
// export default CanvasBoard;

// 单文件使用
window.CanvasBoard = CanvasBoard;
